<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入员工名称或电话"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keyQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table :data="employees" highlight-current-row v-loading="listLoading"
              :row-key="getRowKey" @selection-change="selsChange"
              style="width: 100%;" @row-dblclick="getDbMes">
      <el-table-column type="selection" width="55" :reserve-selection="true">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="username" label="员工名称" width="120"align="center">
      </el-table-column>
      <el-table-column prop="phone" label="员工电话" width="150" align="center">
      </el-table-column>
      <el-table-column prop="email" label="员工邮箱" width="150" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="50" align="center">
      </el-table-column>
      <el-table-column prop="state" label="员工状态" width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: lightseagreen">启用</span>
          <span v-else style="color: crimson">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门" width="100" align="center">
      </el-table-column>
      <el-table-column label="员工身份" width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.shopId == null" style="color: mediumpurple">平台管理</span>
          <span v-else style="color: cornflowerblue">店铺管理</span>
        </template>
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" width="100" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="role.name" label="所属角色" width="100" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="totals"
          :page-sizes="[5, 8, 10]"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加修改对话框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="员工名称" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工邮箱">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="saveForm.id == null">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属店铺">
          <el-select v-model="saveForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属角色">
          <el-select v-model="saveForm.roleId" clearable placeholder="请选择">
            <el-option
                v-for="item in roles"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-cascader
              v-model="saveForm.departmentId"
              :options="deptTree"
              :props="{ checkStrictly: true, label: 'name',value:'id' }"
              clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getemployeeListPage, removeemployee, batchRemoveemployee, editemployee, addemployee } from '../../api/api';

export default {
  watch: {
    saveFormVisible(val) { // 当弹窗打开时
      // 重置表单，清空校验信息
      this.$nextTick(() => {
        //  延时到下一帧才开始，也就是页面刚刚渲染结束！！
        this.$refs.saveForm.clearValidate()
      })
    }
  },
  data() {
    return {
      // 分页相关数据
      currentPage: 1,
      pageSize: 5,
      totals: 0,
      employees: [],
      listLoading: false,
      // 高级查询
      keyword: '',
      // 分页批量选中
      getRowKey(row){
        return row.id;
      },
      // 单个信息对话框默认不显示
      dbFormVisible: false,
      // 所有店铺
      shops: '',
      // 部门树
      deptTree: [],
      // 批量删除
      sels: [],//列表选中列
      //对话框数据
      title: '',
      saveForm: {
        id: null,
        username: '',
        phone: '',
        email: '',
        password: '',
        age: '',
        state: 1,
        departmentId: null,
        shopId: null,
        roleId: null,
      },
      // 角色
      roles: [],
      saveFormVisible: false,//新增界面是否显示
      saveLoading: false, // 加载框
      saveFormRules: { // 表单项校验
        username: [
          { required: true, message: '请输入员工名称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入员工电话', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入员工密码', trigger: 'blur' }
        ]
      },
    }
  },
  methods: {
    //分页查询
    getemployees() {
      let param = {
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/employee", param).then(res=>{
        this.employees = res.data.data
        this.totals = res.data.totals
        this.listLoading = false;
      })
    },
    // 高级查询
    keyQuery(){
      this.currentPage = 1
      this.getemployees();
    },
    //选择第几页时触发
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getemployees();
    },
    //选择每页显示记录条数
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getemployees();
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/employee/" + row.id).then(res=>{
          if (res.data.success){
            let pageTotal = Math.ceil(this.totals/this.pageSize)
            if (this.currentPage != 1 && this.currentPage == pageTotal && (this.totals - 1)%this.pageSize ==0){
              this.currentPage = this.currentPage - 1
            }
            this.getemployees();
          } else {
            this.$message.error("系统繁忙，请稍后重试！【500】")
          }
        }).catch(res=> {
          this.$message.error("系统繁忙，请稍后重试！【400,404,405】")
        })
        this.listLoading = false;
      }).catch(() => { // 取消

      });
    },
    // 选中改变时
    selsChange: function (sels) {
      this.sels = sels.map(obj => obj.id);
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/employee",ids).then(res => {
          this.listLoading = false;
          if(res.data.success){
            //计算总页数
            let totalPage = Math.ceil(this.totals/this.pageSize)
            if(this.currentPage > 1 && this.currentPage==totalPage && (this.totals-this.sels.length)%this.pageSize==0){
              this.currentPage = this.currentPage - 1;
            }
            this.getemployees();
          }else{
            this.$message.error("系统繁忙，请稍后重试![500]");
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试![400]");
        })
      }).catch(() => {
      });
    },
    // 双击获取当前信息
    getDbMes(row){
      this.$http.get("/employee/" + row.id).then(res => {
        this.saveForm = res.data
        this.dbFormVisible = true
      })
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = '编辑'
      this.saveForm = Object.assign({}, row);
      this.getShops();
      this.getRoles();
      this.getDeptTree();
      this.saveFormVisible = true;
    },
    //显示新增界面
    handleAdd: function () {
      this.title = '添加'
      this.saveForm = { // 重置数据
        id: null,
        username: '',
        phone: '',
        email: '',
        password: '',
        age: '',
        state: 1,
        departmentId: null,
        shopId: null,
        roleId: null,
      };
      this.getShops();
      this.getRoles();
      this.getDeptTree();
      this.saveFormVisible = true;
    },
    //提交按钮
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({},this.saveForm)
            // 判断parentId
            let temp = para.departmentId
            if (temp == null || temp.length == 0){ // 顶级部门
              para.departmentId = null;
            } else if (temp.length) { // 子部门 获取id
              para.departmentId = temp[temp.length-1]
            }
            this.$http.put("/employee",para).then(res=>{
              this.saveLoading = false;
              this.saveFormVisible = false;
              if (res.data.success){
                this.getemployees()
                this.$message.success("操作成功！")
              } else {
                this.$message.error("系统繁忙，请稍后重试![500]");
              }
            }).catch(res=>{
              this.$message.error("系统繁忙，请稍后重试![400]");
            })
          });
        }
      });
    },
    // 获取所有店铺
    getShops(){
      this.$http.get("/shop").then(res => {
        this.shops = res.data;
      })
    },
    // 获取部门树
    getDeptTree(){
      this.$http.get("/department/deptTree").then(res => {
        this.deptTree = res.data;
      })
    },
    // 获取角色
    getRoles(){
      this.$http.get("/role").then(res=>{
        this.roles = res.data;
      })
    }
  },
  mounted() {
    this.getemployees();
  }
}

</script>

<style scoped>

</style>